<template>
  <div>
    <el-card>
      <el-alert v-if="!$store.state.method" title="非连接数据库时该页面仅做展示数据使用,不可做增删改查操作!分页效果也会失效" :closable="false" style="margin-bottom: 10px"></el-alert>
      <el-row>
        <el-col>
          <el-button type="primary" @click="initAddArticle">添加文章</el-button>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px;">
        <el-form :model="queryForm" ref="queryFormRef">
          <el-row :gutter="10">
            <el-col :span="5">
              <el-form-item>
                <el-input v-model="queryForm.content" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item>
                <el-select v-model="queryForm.importance" placeholder="重要性" clearable>
                    <el-option v-for="item in importance" :key="item" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item>
                <el-select v-model="queryForm.country" placeholder="区域" clearable>
                    <el-option v-for="(item, index) in country" :key="index" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" class="el-icon-search" size="small" @click="getTableList('init')">搜索</el-button>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" class="el-icon-download" size="small" @click="exportExcel">导出</el-button>
            </el-col>
            <el-col :span="2">
              <el-checkbox v-model="audit" @change="changeAudit($event)">审核人</el-checkbox>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <el-table :data="tableDataList" border id="currentTableData">
        <el-table-column label="序号" prop="serialNumber" sortable  width="80px"></el-table-column>
        <el-table-column label="时间" width="120px">
          <template slot-scope="{row}">
            <span>{{row.date}}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题" prop="title">
          <template slot-scope="{row}">
            <span style="color: #339a9a;">{{row.title}}</span>
            <el-tag size="mini">{{row.country === "" ? 'CHINA' : row.country}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="作者" prop="author" width="80px"></el-table-column>
        <el-table-column label="审核人" v-if="audit" width="90px">
          <template slot-scope="{row}">
            <span style="color: #00C48D;">{{row.audit}}</span>
          </template>
        </el-table-column>
        <el-table-column label="重要性" width="80px">
          <template slot-scope="{row}">
            <i class="el-icon-star-on" v-for="(item, index) in row.importance" :key="index"></i>
          </template>
        </el-table-column>
        <el-table-column label="阅读数" width="80px">
          <template slot-scope="{row}">
            <span style="color: red;">{{row.readings}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100px">
          <template slot-scope="{row}">
            <el-tag type="success" v-if="row.status === 1" size="mini">published</el-tag>
            <el-tag v-else type="info" size="mini">draft</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250px">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="editArticle(row)">编辑</el-button>
            <el-button type="success" v-if="row.status === 0" size="mini" @click="changStatus(row)">发布</el-button>
            <el-button type="infor" v-else size="mini" @click="changStatus(row)">草稿</el-button>
            <el-button type="danger" size="mini" @click="deleteData(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table :data="allTableDataList" id="exportTable" style="display: none;">
        <el-table-column label="序号" prop="serialNumber" sortable  width="80px"></el-table-column>
        <el-table-column label="时间" width="120px">
          <template slot-scope="{row}">
            <span>{{row.date}}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题" prop="title">
          <template slot-scope="{row}">
            <span style="color: #339a9a;">{{row.title}}</span>
            <el-tag size="mini">{{row.country === "" ? 'CHINA' : row.country}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="作者" prop="author" width="80px"></el-table-column>
        <el-table-column label="审核人" v-if="audit" width="90px">
          <template slot-scope="{row}">
            <span style="color: #00C48D;">{{row.audit}}</span>
          </template>
        </el-table-column>
        <el-table-column label="重要性" width="80px">
          <template slot-scope="{row}">
            <i class="el-icon-star-on" v-for="(item, index) in row.importance" :key="index"></i>
          </template>
        </el-table-column>
        <el-table-column label="阅读数" width="80px">
          <template slot-scope="{row}">
            <span style="color: red;">{{row.readings}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100px">
          <template slot-scope="{row}">
            <el-tag type="success" v-if="row.status === 1" size="mini">published</el-tag>
            <el-tag v-else type="info" size="mini">draft</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250px">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="editArticle(row)">编辑</el-button>
            <el-button type="success" v-if="row.status === 0" size="mini" @click="changStatus(row)">发布</el-button>
            <el-button type="infor" v-else size="mini" @click="changStatus(row)">草稿</el-button>
            <el-button type="danger" size="mini" @click="deleteData(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="getCurrentSizeData" @current-change="getCurrentPageData" :current-page="queryForm.currentPage" :page-sizes="[3, 5, 8, 12]" :page-size="queryForm.currentNum" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </el-card>
    <el-dialog title="添加文章" :visible.sync="isAddArticleDialog" @close="clearFormData" :close-on-click-modal="false" width="50%">
      <el-form :model="articleData" ref="addArticleFormRef" :rules="addArticleFormRules" label-width="100px">
        <el-form-item label="Title" prop="title">
          <el-input v-model="articleData.title"></el-input>
        </el-form-item>
        <el-form-item label="Author" prop="author">
          <el-input v-model="articleData.author"></el-input>
        </el-form-item>
        <el-form-item label="Importance" prop="importance">
          <el-rate v-model="articleData.importance" :max="3"></el-rate>
        </el-form-item>
        <el-form-item label="Status" prop="status">
          <el-select v-model="articleData.status" placeholder="状态">
              <el-option v-for="item in status" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Country" prop="country">
          <el-select v-model="articleData.country">
            <el-option v-for="(item, index) in country" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="infor" @click="isAddArticleDialog = false">取消</el-button>
        <el-button type="primary" @click="addArticle">添加</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
export default {
  data() {
    return {
      isAddArticleDialog: false,
      addArticleQuery: {
        title: '',
        author: '',
        importance: 1,
        status: 0,
        country: 'CHINA'
      },
      allTableDataList: [],
      articleData: {
        title: '',
        author: '',
        importance: 1,
        status: 0,
        country: 'CHINA'
      },
      editArticleQuery: undefined,
      addArticleFormRules: {
        title: [
          { required: true, message: '请填写标题', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请填写作者', trigger: 'blur' }
        ],
        importance: [
        ],
        status: [
        ],
        country: [
        ]
      },
      queryForm: {
        content: undefined,
        country: undefined,
        importance: undefined,
        currentPage: 1,
        currentNum: 3
      },
      importance: undefined,
      country: undefined,
      idOrder: undefined,
      status: undefined,
      audit: false,
      tableDataList: [],
      edit: false,
      total: 0
    }
  },
  created() {
    this.getArticleParams()
    this.getTableList()
    this.getAllTableList()
  },
  methods: {
    async exportExcel() {
      const confirm = await this.$confirm('导出全部还是导出当前页数据', '导出数据提示', {
        confirmButtonText: '全部',
        cancelButtonText: '当前页',
        type: 'warning'
      }).catch(err => err)
      let wb = ''
      if(confirm !== 'confirm') {
        wb = XLSX.utils.table_to_book(document.querySelector('#currentTableData'))
      }else {
        wb = XLSX.utils.table_to_book(document.querySelector('#exportTable'))
      }
      const wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          'sheetjs.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    getCurrentPageData(val) {
      this.queryForm.currentPage = val
      this.getTableList()
    },
    getCurrentSizeData(val) {
      this.queryForm.currentNum = val
      this.getTableList()
    },
    initAddArticle() {
      this.articleData = this.addArticleQuery
      this.isAddArticleDialog = true
    },
    addArticle() {
      this.$refs.addArticleFormRef.validate(async valid => {
        if(!valid) return
        if(this.edit) {
          const res = await this.$http.put('edit/article/' + this.articleData.serialNumber, this.articleData)
          if(!res.ok) return this.$message({ type: 'error', message: '修改失败', duration: 2000 })
          this.$message({ type: 'success', message: '修改成功', duration: 2000 })
          this.getTableList()
          this.edit = false
          this.isAddArticleDialog = false
          return
        }
        const res = await this.$http.post('edit/article', this.addArticleQuery)
        if(!res) return this.$message({ type: 'error', message: '添加失败', duration: 2000 })
        this.$message({ type: 'success', message: '添加成功', duration: 2000 })
        this.getTableList()
        this.isAddArticleDialog = false
      })
    },
    getArticleParams() {
      this.country = ['CHINA', 'USA', 'JAPAN', 'EUROZONE']
      this.importance = [1, 2, 3]
      this.idOrder = ['ascending', 'descending']
      this.status = [0, 1]
    },
    async getAllTableList() {
      if(!this.$store.state.method) {
        this.queryForm.method = false
      }
      const res = await this.$http.get('edit/article', { params: this.queryForm })
      res.response.forEach(item => {
        if(!this.queryForm.method) {
          item.date = item.date.$date.split('T')[0]
          return
        }
        item.date = item.date.split('T')[0]
      })
      this.allTableDataList = res.response
      console.log(this.allTableDataList)
    },
    async getTableList(type) {
      if(type) {
        this.queryForm.currentPage = 1
      }
      if(!this.$store.state.method) {
        this.queryForm.method = false
      }
      const res = await this.$http.get('edit/article', { params: this.queryForm })
      res.response.forEach(item => {
        if(!this.$store.state.method) {
          item.date = item.date.$date.split('T')[0]
          return
        }
        item.date = item.date.split('T')[0]
      })
      this.tableDataList = res.response
      if(!this.$store.state.method) {
        this.total = res.response.length
      }else {
        this.total = res.total
      }
    },
    changeAudit(e) {
      this.audit = e
    },
    clearFormData() {
      this.$refs.addArticleFormRef.resetFields()
    },
    async changStatus(row) {
      const id = row.serialNumber
      let statusCode = row.status
      statusCode = statusCode === 1 ? 0 : 1
      const res = await this.$http.put('edit/article/' + id, { status: statusCode })
      if(!res.ok) return this.$message.error('修改失败')
      this.getTableList()
    },
    async deleteData(row) {
      const confirm = await this.$confirm('去定要删除该条数据吗？', '删除警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(confirm !== 'confirm') return this.$message({ type: 'info', message: '已取消删除操作', duration: 2000 })
      const id = row.serialNumber
      const res = await this.$http.delete('edit/article/' + id)
      if(!res.ok) return this.$message.error('删除失败')
      this.getTableList()
    },
    editArticle(row) {
      this.edit = true
      this.articleData = row
      this.isAddArticleDialog = true
    }
  }
}
</script>

<style scoped>
  .el-form-item {
    margin-bottom: 0;
  }
  .el-dialog .el-form-item {
    margin: 20px 0;
  }
  .el-table {
    margin-top: 20px;
  }
  .el-tag {
    transition: none!important;
  }
</style>
